//
//  QueRenDingDanViewController.m
//  1243
//
//  Created by 我的 on 16/4/20.
//  Copyright © 2016年 1243. All rights reserved.
//

#import "QueRenDingDanViewController.h"
#import "ConfirmTableViewCell.h"
#import "ManagerViewController.h"
#import "ZhiFuViewController.h"
#import "UIImageView+WebCache.h"
#import "NetWorkTools.h"
#import "ChooseAddressTableViewController.h"
#import "gerAddressController.h"
#import "ShopCartViewController.h"
#import "JudgeUserLogInTool.h"
#import "LoginViewController.h"


#import "gerAddressController.h"

@interface QueRenDingDanViewController ()<UITableViewDelegate, UITableViewDataSource,UIAlertViewDelegate>
{
    NSDictionary *GetAddressDict;
}

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UILabel *Allprice;

@property (nonatomic, strong) NSDictionary *dic;

@property (nonatomic,strong)NSMutableArray *orderArray;

@end

@implementation QueRenDingDanViewController


- (NSMutableArray *)orderArray {
    if (!_orderArray) {
        _orderArray = [NSMutableArray array];
    }
    return _orderArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"确认订单";
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 49) style:UITableViewStyleGrouped];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ConfirmTableViewCell" bundle:nil] forCellReuseIdentifier:@"ConfirmTableViewCell"];
    
    [self.view addSubview:self.tableView];
    NSLog(@"%f", self.allPrice);
    
    [self addFooterView];
    [self shopCarButton];
    
  
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getAddress:) name:@"gankuaifagongzi" object:nil];
}

- (void)getAddress:(NSNotification *)noti {
    
    GetAddressDict = noti.userInfo[@"CardInfo"];
    [self.tableView reloadData];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];

      [self loadUserAddressData];
    
    self.dic = [ReadLoginData readLoginData];
    NSLog(@"%@",self.dic);
    


}

//FooterView
- (void)addFooterView {
    
    //底层的view
    UIView *firstView = [[UIView alloc] initWithFrame:CGRectMake(0, HIGHT - 49, (WEITH/3)*2, 49)];
    firstView.backgroundColor = [UIColor whiteColor];
    firstView.layer.borderWidth = .6;
    firstView.layer.borderColor = [UIColor grayColor].CGColor;//[UIColor colorWithRed:244/255. green:244/255. blue:244/255. alpha:1].CGColor;
    [self.view addSubview:firstView];
    
    UIButton *sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    sureBtn.frame = CGRectMake((WEITH/3)*2, HIGHT - 49, WEITH/3, 49);
    [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    sureBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    sureBtn.backgroundColor = [UIColor colorWithRed:52/255. green:147/255. blue:225/255. alpha:1];
    [sureBtn addTarget:self action:@selector(sureButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sureBtn];
    
    UILabel *translabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetWidth(firstView.frame)-60, 5, 60, CGRectGetHeight(firstView.frame)-10)];
    translabel.text = @"含运费";
    translabel.font = [UIFont systemFontOfSize:11];
    [firstView addSubview:translabel];
    
    self.Allprice = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(translabel.frame)-80, 5, 80, CGRectGetHeight(firstView.frame)-10)];
    self.Allprice.textColor = [UIColor redColor];
    if (self.num == 0) {
        self.Allprice.text = [NSString stringWithFormat:@"¥%.2f", [self.shopDic[@"SellPrice"] floatValue] * [self.shopDic[@"buyNum"] integerValue]];
    } else {
        self.Allprice.text = [NSString stringWithFormat:@"¥%.2f", self.allPrice];
    }
    self.Allprice.textAlignment = NSTextAlignmentLeft;
    self.Allprice.font = [UIFont systemFontOfSize:12.5];
    [firstView addSubview:self.Allprice];
    
    UILabel *otherlabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(self.Allprice.frame)-60, 5, 60, CGRectGetHeight(firstView.frame)-10)];
    otherlabel.text = @"合计:  ";
    otherlabel.textAlignment = NSTextAlignmentRight;
    otherlabel.font = [UIFont systemFontOfSize:12.5];
    [firstView addSubview:otherlabel];
    
}

/**
 *  购物车按钮
 */

- (void)shopCarButton
{
    UIButton *shopCart = [[UIButton alloc] init];
    
    [shopCart addTarget:self action:@selector(clickShopCart) forControlEvents:UIControlEventTouchUpInside];
    [shopCart setImage:[UIImage imageNamed:@"gouwuche"] forState:UIControlStateNormal];
    [shopCart setFrame:CGRectMake(WIDTH - 60, HEIGHT - 170+64, 30, 30)];
    [shopCart setImage:[UIImage imageNamed:@"gouwuche"] forState:UIControlStateNormal];
    [self.view addSubview:shopCart];
}

- (void)clickShopCart {
    NSLog(@"...");
    if ([JudgeUserLogInTool JudgeUserLonInStatus]) {
        
        [self.navigationController pushViewController:[[ShopCartViewController alloc] init] animated:YES];
    }else{
        LoginViewController *a = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:[NSBundle mainBundle]];
        [self presentViewController:a animated:YES completion:nil];
        
    }
}


/**
 *  点击确定按钮
 */
/**
 *  创建订单
 */
- (void)sureButtonClick{
    NSLog(@"...");
    NSArray *shopDict = [NSArray array];
    if (self.num == 0) {
        shopDict = @[self.shopDic];
    } else {
        shopDict = [ReadLoginData readShopArr];
    }
    
    
    
    NSLog(@"%@",shopDict);
    
    if (self.dingDanArrM.count && GetAddressDict.count) {
        NSDictionary *dict = [ReadLoginData readLoginData];
        
        NSString *userId = [dict objectForKey:@"Number"];
        
        NSMutableArray *orderArray = [NSMutableArray array];
        
        NSString *userName = [dict objectForKey:@"UserName"];
        
        NSString *buyNum = @"";
        
        NSString *productId = @"";
        
        for (int i = 0; i < self.dingDanArrM.count; i ++) {
            if (i == 0) {
                buyNum = [buyNum stringByAppendingString:[NSString stringWithFormat:@"%@", self.dingDanArrM[i][@"buyNum"]]];
                productId = [productId stringByAppendingString:[NSString stringWithFormat:@"%@", self.dingDanArrM[i][@"Id"]]];
            } else {
                buyNum = [buyNum stringByAppendingString:[NSString stringWithFormat:@"|%@", self.dingDanArrM[i][@"buyNum"]]];
                productId = [productId stringByAppendingString:[NSString stringWithFormat:@"|%@", self.dingDanArrM[i][@"Id"]]];
            }
        }
        
        NSLog(@"%@----%@", buyNum, productId);
        
        
        /*
         //ri.MenthodName = "CREATEORDERMUT";
         
         //co.UserId = "1001";
         //co.UserName = "18906539951";
         //co.BuyNum = "1|2";
         //co.ProductId = "53877|53878";//价格 10，12
         //co.ReceiveAddress = "浙江省杭州市文二路节能公司";
         //co.ReceiveCity = "杭州";
         //co.ReceiveMobile = "18906539950";
         //co.ReceiveName = "麦西";
         //co.ReceivePhone = "";
         //co.ReveiveProvice = "";
         */
        NSDictionary *params = @{
                                 @"UserId":userId,
                                 @"UserName":userName,
                                 @"ProductId":productId,
                                 @"BuyNum":buyNum,
                                 @"ReceiveName":[GetAddressDict objectForKey:@"ContactName"],
                                 @"ReceiveMobile":[GetAddressDict objectForKey:@"ContactPhone"],
                                 @"ReceivePhone":[GetAddressDict objectForKey:@"ContactPhone"],
                                 @"ReveiveProvice":[GetAddressDict objectForKey:@"Province"],
                                 @"ReceiveCity":[GetAddressDict objectForKey:@"City"],
                                 @"ReceiveAddress":[GetAddressDict objectForKey:@"Address"]
                                 };
        
        [[NetWorkTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"CREATEORDERMUT" completeBlock:^(id object) {
            
            if ([object[@"Id"] isEqual:@(0)]) {
                [orderArray addObject:[object objectForKey:@"BackData"]];
                
                ZhiFuViewController *zhiFuVC = [[ZhiFuViewController alloc] init];
                if (self.num == 0) {
                    zhiFuVC.allPrice = [self.shopDic[@"SellPrice"] floatValue] * [self.shopDic[@"buyNum"] integerValue];
                } else {
                    
                    zhiFuVC.allPrice = self.allPrice;
                }
                zhiFuVC.num = self.num;
                zhiFuVC.orderArray = orderArray;
                zhiFuVC.number = self.shopDic[@"buyNum"];
                zhiFuVC.str = self.str;
                [self.navigationController pushViewController:zhiFuVC animated:YES];
            }else{
                
                NSString *str = [object objectForKey:@"Message"];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:str delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
                alert.tag = 1000;
                [alert show];
            }
            
        }];
        

    } else {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请输入收货人地址" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1000) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}


#pragma mark - UITableView DataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 1) {
        if (self.num == 0) {
            return 1;
        } else {
            return self.dingDanArrM.count;
        }
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        
        static NSString *ID = @"cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
        }
        cell.imageView.image = [UIImage imageNamed:@"定位"];
        
        if (!GetAddressDict.count ) {
            
            cell.textLabel.text = [NSString stringWithFormat:@"姓名:未填写  手机:未填写"];
            cell.detailTextLabel.text= [NSString stringWithFormat:@"未填写"];
        
        } else {
            
        
            
            cell.textLabel.text = [NSString stringWithFormat:@"姓名:%@  手机:%@", GetAddressDict[@"ContactName"], GetAddressDict[@"ContactPhone"]];
            cell.detailTextLabel.text= [NSString stringWithFormat:@"%@%@%@%@", GetAddressDict[@"Province"],GetAddressDict[@"City"],GetAddressDict[@"Countory"],GetAddressDict[@"Address"]];
        }
        
        return cell;
    } else if (indexPath.section == 1) {
        
        ConfirmTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ConfirmTableViewCell" forIndexPath:indexPath];
        if (self.num == 0) {
            [cell.shopImageV sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://120.76.162.124:8083%@", self.shopDic[@"PictureURL"]]]];
            cell.shopTitle.text = self.shopDic[@"Title"];
            cell.shopPrice.text = [NSString stringWithFormat:@"%@",self.shopDic[@"SellPrice"]];
            cell.shopNum.text = [NSString stringWithFormat:@"x%@", self.shopDic[@"buyNum"]];
        } else {
            
            [cell.shopImageV sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://120.76.162.124:8083%@", self.dingDanArrM[indexPath.row][@"PictureURL"]]]];
            cell.shopTitle.text = self.dingDanArrM[indexPath.row][@"Title"];
            cell.shopPrice.text = [NSString stringWithFormat:@"%@",self.dingDanArrM[indexPath.row][@"SellPrice"]];
            cell.shopNum.text = [NSString stringWithFormat:@"x%@", self.dingDanArrM[indexPath.row][@"buyNum"]];
        }
        
        
        return cell;
    } else {
        static NSString *ID = @"cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
        }
        
        
        cell.textLabel.text = @"配送方式";
        cell.detailTextLabel.text= @"快递 ";
        
        return cell;
    }
    
}

#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 80;
    } else if (indexPath.section == 1) {
        return 110;
        
    }else {
        return 60;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 4 || section == 3) {
        return 35;
    } else {
        return 20;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 2) {
        return 30;
    }
    return 5.01;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {

    UIView *footerView = [[UIView alloc] init];

    if (section == 2) {
  
        footerView.backgroundColor = [UIColor colorWithRed:48 / 255.0 green:123 / 255.0 blue:225 / 255.0 alpha:1];
        UILabel *numLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 5, 160, 20)];
        
        [footerView addSubview:numLabel];
        UILabel *priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(WEITH - 88, 5, 80, 20)];
        [footerView addSubview:priceLabel];
        priceLabel.textColor = [UIColor blackColor];
        priceLabel.font = [UIFont systemFontOfSize:14];
        UILabel *otherLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(priceLabel.frame)-50, 5, 50, 20)];
        otherLabel.textAlignment = NSTextAlignmentRight;
        otherLabel.font = [UIFont systemFontOfSize:14];
        [footerView addSubview:otherLabel];
        
        
        otherLabel.text = @"合计:  ";
        if (self.num == 0) {
            
            numLabel.text = [NSString stringWithFormat:@"共计%@件", self.shopDic[@"buyNum"]];
            priceLabel.text = [NSString stringWithFormat:@"¥%.2f", [self.shopDic[@"SellPrice"] floatValue] * [self.shopDic[@"buyNum"] integerValue]];
        } else {
            
            numLabel.text = [NSString stringWithFormat:@"共计%zd件", self.dingDanArrM.count];
            priceLabel.text = [NSString stringWithFormat:@"¥%.2f", self.allPrice];
        }
        
        
    }
    
    
    return footerView;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        
        gerAddressController *mangerVC = [[gerAddressController alloc] init];
        
        mangerVC.pageIndex = 0;
        [self.navigationController pushViewController:mangerVC animated:YES];
        
    }
    
}


#pragma mark>>>>> 获取地址
- (void)loadUserAddressData {

    NSDictionary *userData = [ReadLoginData readLoginData];
    
    NSString *userId = [userData objectForKey:@"Number"];
    
    NSDictionary *params = @{
                             //
                             @"UserId":userId
                             };
    
    [[NetWorkTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"EXPRESSQUERY" completeBlock:^(id object) {
        //        NSLog(@"%@",object);
        
        NSLog(@"%@",[object objectForKey:@"BackData"]);
        
        NSString *string = [object objectForKey:@"BackData"];
        NSArray *arr = [NetWorkTools arrayWithJsonString:string];
        
        GetAddressDict = arr[0];
 
        [self.tableView reloadData];
        
    }];
}



@end
